<template>
	<view class="profile-info-container">
		<!-- 导航栏 -->
		<ob-navbar
			title="个人资料"
			:show-back="true"
			:prevent-default-back="true"
			@left-click="handleBack"
		>
			<template #right>
				<text class="save-btn" @click="saveProfile">保存</text>
			</template>
		</ob-navbar>
		<br></br>
		<!-- 表单内容 -->
		<scroll-view class="form-content" scroll-y="true">
			<br></br>
			<!-- 头像设置 -->
			<view class="form-section">
				<view class="section-title">头像设置</view>
				<view class="avatar-setting" @click="changeAvatar">
					<image class="user-avatar" :src="avatarSrc" mode="aspectFill" />
					<view class="avatar-overlay">
						<text class="camera-icon">📷</text>
						<text class="change-text">更换头像</text>
					</view>
				</view>
			</view>

			<!-- 基础信息 -->
			<view class="form-section">
				<view class="section-title">基础信息</view>
				<view class="form-list">
					<view class="form-item">
						<text class="item-label">用户名</text>
						<input
							class="item-input"
							type="text"
							v-model="formData.username"
							placeholder="请输入用户名"
							maxlength="20"
							@blur="validateUsername"
						/>
						<text v-if="usernameError" class="item-error">{{ usernameError }}</text>
					</view>
					<view class="form-item">
						<text class="item-label">昵称</text>
						<input
							class="item-input"
							type="text"
							v-model="formData.nickname"
							placeholder="请输入昵称"
							maxlength="20"
							@blur="validateNickname"
						/>
						<text v-if="nicknameError" class="item-error">{{ nicknameError }}</text>
					</view>
					<view class="form-item">
						<text class="item-label">邮箱</text>
						<input
							class="item-input"
							type="text"
							v-model="formData.email"
							placeholder="请输入邮箱"
							disabled
						/>
						<text class="item-tip">邮箱不可修改</text>
					</view>
					<view class="form-item">
						<text class="item-label">联系电话</text>
						<input
							class="item-input"
							type="number"
							v-model="formData.phone"
							placeholder="请输入联系电话"
							maxlength="11"
							@blur="validatePhone"
						/>
						<text v-if="phoneError" class="item-error">{{ phoneError }}</text>
					</view>
					<view class="form-item">
						<text class="item-label">真实姓名</text>
						<input
							class="item-input"
							type="text"
							v-model="formData.realName"
							placeholder="请输入真实姓名"
							maxlength="20"
							disabled
						/>
						<text class="item-tip">真实姓名不可修改</text>
					</view>
				</view>
			</view>

			<!-- 认证信息 -->
			<view class="form-section">
				<view class="section-title">认证信息</view>
				<view class="form-list">
					<view class="form-item">
						<text class="item-label">邮箱验证</text>
						<text class="item-value" :class="{ 'status-verified': formData.emailVerified === 1, 'status-unverified': formData.emailVerified === 0 }">
							{{ formData.emailVerified === 1 ? '已验证' : '未验证' }}
						</text>
					</view>
					<view class="form-item">
						<text class="item-label">海员认证</text>
						<text class="item-value" :class="getSailorAuthClass(formData.sailorAuthStatus)">
							{{ getSailorAuthText(formData.sailorAuthStatus) }}
						</text>
						<text class="item-arrow" v-if="formData.sailorAuthStatus === 0">></text>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 加载组件 -->
		<ob-loading :visible="isLoading" text="保存中..." />
	</view>
</template>

<script setup>
import { ref, computed, inject, onMounted } from 'vue'
import { getEnv } from '../../utils/env.js'
import userApi from '../../api/user.js'

// 全局状态
const store = inject('$store')

// 响应式数据 - 基于新的User实体类字段
const formData = ref({
	avatar: '',
	username: '',
	nickname: '',
	email: '',
	phone: '',
	realName: '', // 新实体类字段
	countryId: null, // 新实体类字段
	sailorAuthStatus: 0, // 新实体类字段
	emailVerified: 0 // 新实体类字段


})

const isLoading = ref(false)

// 表单验证错误状态
const usernameError = ref('')
const nicknameError = ref('')
const phoneError = ref('')

// 头像URL标准化：兼容相对/绝对路径，Minio 网关路径从环境前缀拼接
const resolveAvatar = (url) => {
  if (!url) return ''
  if (url.startsWith('http')) return url
  const base = getEnv('VUE_APP_BASE_API', '')
  const path = url.startsWith('/') ? url : `/${url}`
  return base ? `${base}${path}` : path
}

const avatarSrc = computed(() => resolveAvatar(formData.value.avatar))

// 表单验证函数
const validateUsername = () => {


	if (!formData.value.username || !formData.value.username.trim()) {
		usernameError.value = '用户名不能为空'
		return false
	}

	if (formData.value.username.length < 2) {
		usernameError.value = '用户名至少需要2个字符'
		return false
	}

	usernameError.value = ''
	return true
}

const validateNickname = () => {
	if (!formData.value.nickname || !formData.value.nickname.trim()) {
		nicknameError.value = '昵称不能为空'
		return false
	}

	if (formData.value.nickname.length < 1) {
		nicknameError.value = '昵称不能为空'
		return false
	}

	nicknameError.value = ''
	return true
}

const validatePhone = () => {
	// 手机号是可选的，但如果提供了就需要验证格式
	if (formData.value.phone && formData.value.phone.trim()) {
		if (!/^1[3-9]\d{9}$/.test(formData.value.phone)) {
			phoneError.value = '手机号格式不正确'
			return false
		}
	}

	phoneError.value = ''
	return true
}

// 验证所有表单字段
const validateForm = () => {
	const isUsernameValid = validateUsername()
	const isNicknameValid = validateNickname()
	const isPhoneValid = validatePhone()

	return isUsernameValid && isNicknameValid && isPhoneValid
}

// 页面加载
onMounted(() => {
	loadUserProfile()
})

// 处理返回按钮点击 - 简化版本，直接跳转到个人中心
const handleBack = () => {
	uni.switchTab({
		url: '/pages/profile/index'
	})
}

// 更换头像
const changeAvatar = () => {
	uni.chooseImage({
		count: 1,
		sizeType: ['compressed'],
		sourceType: ['album', 'camera'],
		success: async (res) => {
			try {
				uni.showLoading({
					title: '上传中...'
				})

				// 上传头像到后端
				const uploadResponse = await userApi.uploadAvatar(res.tempFilePaths[0])

				// 更新本地头像显示 - 使用后端返回的avatarUrl
				if (uploadResponse && uploadResponse.avatarUrl) {
					formData.value.avatar = uploadResponse.avatarUrl

					// 更新全局用户状态
					if (store && store.actions && store.actions.setUserInfo) {
						const currentUserInfo = uni.getStorageSync('userInfo') || {}
						const updatedUserInfo = {
							...currentUserInfo,
							avatar: uploadResponse.avatarUrl
						}
						store.actions.setUserInfo(updatedUserInfo)
						uni.setStorageSync('userInfo', updatedUserInfo)
					}
				}

				uni.hideLoading()
				uni.showToast({
					title: '头像更新成功',
					icon: 'success'
				})

			} catch (error) {
				uni.hideLoading()
				console.error('上传头像失败:', error)
				uni.showToast({
					title: error.message || '上传失败',
					icon: 'none'
				})
			}
		}
	})
}

// 获取海员认证状态文本
const getSailorAuthText = (status) => {
	switch (status) {
		case 0:
			return '未认证'
		case 1:
			return '已认证'
		case 2:
			return '审核中'
		default:
			return '未知'
	}
}

// 获取海员认证状态样式
const getSailorAuthClass = (status) => {
	switch (status) {
		case 0:
			return 'status-unverified'
		case 1:
			return 'status-verified'
		case 2:
			return 'status-pending'
		default:
			return 'status-unknown'
	}
}

// 加载用户资料
const loadUserProfile = async () => {
	try {
		isLoading.value = true
		console.log('🚀 开始加载用户资料...')

		// 检查是否已登录
		const userInfo = uni.getStorageSync('userInfo')
		const accessToken = uni.getStorageSync('accessToken')

		if (!accessToken && !userInfo) {
			// 在开发阶段，如果没有登录信息，设置测试用户ID
			if (!uni.getStorageSync('userId')) {
				uni.setStorageSync('userId', 16) // 使用测试ID
			}
		} else if (userInfo && userInfo.id) {
			uni.setStorageSync('userId', userInfo.id)
		}

		// 调用API获取用户资料
		const userData = await userApi.getUserProfile()

		if (userData) {
			console.log('✅ 用户资料加载成功:', userData)

			// 更新表单数据
			formData.value = {
				avatar: userData.avatar || '',
				username: userData.username || '',
				nickname: userData.nickname || '',
				email: userData.email || '',
				phone: userData.phone || '',
				realName: userData.realName || '',
				countryId: userData.countryId || null,
				sailorAuthStatus: userData.sailorAuthStatus || 0,
				emailVerified: userData.emailVerified || 0
			}
		} else {
			console.warn('⚠️ 用户资料为空')
		}

	} catch (error) {
		console.error('❌ 加载用户资料失败:', error)

		if (error.message && error.message.includes('401')) {
			uni.showModal({
				title: '登录已过期',
				content: '请重新登录',
				confirmText: '去登录',
				showCancel: false,
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: '/pages/auth/login'
						})
					}
				}
			})
		} else {
			// 显示错误信息
			uni.showToast({
				title: `加载失败: ${error.message || '未知错误'}`,
				icon: 'none',
				duration: 3000
			})
		}
	} finally {
		isLoading.value = false
	}
}

// 保存用户资料
const saveProfile = async () => {
	// 清除之前的错误状态
	usernameError.value = ''
	nicknameError.value = ''
	phoneError.value = ''

	// 表单验证
	if (!validateForm()) {
		uni.showToast({
			title: '请检查输入信息',
			icon: 'none',
			duration: 2000
		})
		return
	}

	try {
		isLoading.value = true
		console.log('🚀 开始保存用户资料...')

		// 构建更新数据
		const updateData = {
			nickname: formData.value.nickname.trim(),
			username: formData.value.username.trim(),
			phone: formData.value.phone ? formData.value.phone.trim() : ''
		}

		console.log('📤 发送更新数据:', updateData)

		// 调用API更新用户资料
		const result = await userApi.updateUserProfile(updateData)

		if (result === true) {
			// 重新获取最新的用户信息
			const updatedUserData = await userApi.getUserProfile()

			// 更新表单数据
			if (updatedUserData) {
				formData.value = {
					...formData.value,
					nickname: updatedUserData.nickname || '',
					username: updatedUserData.username || '',
					phone: updatedUserData.phone || '',
					email: updatedUserData.email || ''
				}

				// 更新全局状态
				if (store && store.actions && store.actions.setUserInfo) {
					store.actions.setUserInfo(updatedUserData)
				}

				// 同步更新本地存储的用户信息
				uni.setStorageSync('userInfo', updatedUserData)
			}

			uni.showToast({
				title: '保存成功',
				icon: 'success',
				duration: 2000
			})

			// 延迟返回个人中心
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/profile/index'
				})
			}, 2000)
		} else {
			uni.showToast({
				title: '保存失败，请重试',
				icon: 'none',
				duration: 3000
			})
		}

	} catch (error) {
		console.error('保存用户资料失败:', error)

		// 根据错误类型提供更具体的错误提示
		let errorMessage = '保存失败'

		if (error.message) {
			if (error.message.includes('400')) {
				errorMessage = '请求参数错误，请检查输入内容'
			} else if (error.message.includes('401')) {
				errorMessage = '登录已过期，请重新登录'
			} else if (error.message.includes('404')) {
				errorMessage = '接口地址不存在，请检查配置'
			} else if (error.message.includes('500')) {
				errorMessage = '服务器内部错误，请稍后重试'
			} else {
				errorMessage = error.message
			}
		}

		uni.showToast({
			title: errorMessage,
			icon: 'none',
			duration: 3000
		})
	} finally {
		isLoading.value = false
	}
}

</script>

<style lang="scss" scoped>
.profile-info-container {
	background: #F5F5F5;
	min-height: 100vh;
}

.save-btn {
	color: var(--primary-color);
	font-size: 16px;
	font-weight: 500;
}

.form-content {
	flex: 1;
	padding: 15px;
}

.form-section {
	background: #FFFFFF;
	border-radius: 12px;
	margin-bottom: 15px;
	overflow: hidden;
}

.section-title {
	font-size: 16px;
	font-weight: 600;
	color: #333333;
	padding: 20px 20px 10px;
}

.avatar-setting {
	display: flex;
	justify-content: center;
	padding: 20px;
	position: relative;
}

.user-avatar {
	width: 100px;
	height: 100px;
	border-radius: 50px;
	background: #F0F0F0;
}

.avatar-overlay {
	position: absolute;
	bottom: 25px;
	right: 50%;
	transform: translateX(50%);
	background: rgba(0, 0, 0, 0.6);
	border-radius: 12px;
	padding: 4px 8px;
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 4px;
}

.camera-icon {
	font-size: 12px;
	color: #FFFFFF;
}

.change-text {
	font-size: 10px;
	color: #FFFFFF;
}

.form-list {

}

.form-item {
	display: flex;
	align-items: center;
	padding: 15px 20px;
	border-bottom: 1px solid #F8F9FA;

	&:last-child {
		border-bottom: none;
	}

	&.picker-item:active {
		background: #F8F9FA;
	}
}

.item-label {
	font-size: 16px;
	color: #333333;
	width: 80px;
	flex-shrink: 0;
}

.item-input {
	flex: 1;
	font-size: 16px;
	color: #333333;
	text-align: right;
	background: transparent;
	border: none;

	&::placeholder {
		color: #CCCCCC;
	}
}

.item-textarea {
	flex: 1;
	min-height: 80px;
	font-size: 16px;
	color: #333333;
	background: transparent;
	border: none;
	text-align: right;

	&::placeholder {
		color: #CCCCCC;
	}
}

.item-value {
	flex: 1;
	font-size: 16px;
	color: #333333;
	text-align: right;

	&.placeholder {
		color: #CCCCCC;
	}
}

.item-tip {
	font-size: 12px;
	color: #999999;
	margin-left: 8px;
}

.item-arrow {
	font-size: 14px;
	color: #CCCCCC;
	margin-left: 8px;
}

.item-error {
	font-size: 12px;
	color: #FF3B30;
	margin-left: 8px;
	margin-top: 4px;
}

.status-verified {
	color: #4CAF50;
	font-weight: 500;
}

.status-unverified {
	color: #FF9800;
	font-weight: 500;
}

.status-pending {
	color: #2196F3;
	font-weight: 500;
}

.status-unknown {
	color: #999999;
	font-weight: 500;
}
</style>
